package com.anc.web.configuration;

import com.anc.web.handler.WebControllerExceptionHandler;
import org.hibernate.validator.HibernateValidator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.support.ErrorPageFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

/**
 * @Desciption: 需要自动配置的bean
 * @author: Anc
 * @date: 2022/7/01
 */
@Configuration
public class WebConfiguration {

    @Bean
    @ConditionalOnMissingBean(WebControllerExceptionHandler.class)
    public WebControllerExceptionHandler controllerExceptionHandler() {
        return new WebControllerExceptionHandler();
    }

    @Bean
    public ErrorPageFilter errorPageFilter() {
        return new ErrorPageFilter();
    }

    /**
     * 移除errorPageFilter
     *
     * @param filter
     * @return
     */
    @Bean
    public FilterRegistrationBean disableSpringBootErrorFilter(ErrorPageFilter filter) {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(filter);
        filterRegistrationBean.setEnabled(false);
        Validation.byDefaultProvider()
            .configure()
            .getDefaultMessageInterpolator();
        return filterRegistrationBean;
    }

    /**
     * 参数校验器
     *
     * @return
     */
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
        /**设置validator模式为快速失败返回*/
        postProcessor.setValidator(validator());
        return postProcessor;
    }

    @Bean
    public Validator validator() {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
            .configure()
            .addProperty("hibernate.validator.fail_fast", "true")
            .buildValidatorFactory();
        Validator validator = validatorFactory.getValidator();
        return validator;
    }
}
